package com.htwy.ext;

import com.jfinal.core.Const;
import com.jfinal.template.source.ISource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by htwy on 2017/6/27.
 */
public class InputSteamStringSource implements ISource {

    private InputStream steam = null;
    private String key = null;

    public InputSteamStringSource(String key, InputStream steam){
        this.steam = steam;
        this.key = key;
    }

    @Override
    public boolean isModified() {
        return false;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public StringBuilder getContent() {
        StringBuilder ret = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(steam, getEncoding()));
            String line = br.readLine();
            if (line != null) {
                ret.append(line);
            } else {
                return ret;
            }

            while ((line=br.readLine()) != null) {
                ret.append("\n").append(line);
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    com.jfinal.kit.LogKit.error(e.getMessage(), e);
                }
            }
        }
    }

    @Override
    public String getEncoding() {
        return Const.DEFAULT_ENCODING;
    }
}
